package practice;

public class NumArray2 {

    private int[] sum;  // sum[i] 存储前 i 个元素的和
                        // sum[i] 实际存储的是 nums[0...i-1]的和

    private int[] data; //nums的拷贝

    public NumArray2(int[] nums){

        data = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            data[i] = nums[i];
        }

        sum = new int[nums.length + 1];
        sum[0] = 0;
        for (int i = 0; i < sum.length; i++) {
            sum[i] = sum[i-1] + nums[i-1];
        }

    }

    public int sumRange(int i,int j){
        return sum[j+1] - sum[i];
    }

    public void update(int index,int val){
        //当update的时候，sum[] 也会变化
        data[index] = val;
        //从 i+1的位置凯德更新
        for (int i = index+1; i < sum.length; i++) {
            sum[i] = sum[i-1] + data[i-1];
        }
    }



}
